<?php

namespace App\ApiBackend;

use App\Http\Controllers\ApiBaseController;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

/**
 *  上传图片
 */
class UploadImg extends ApiBaseController
{
  private array $fileAllowType = [
    'png',
    'jpg',
    'gif',
  ];
  private float $fileAllowSize = 0.6;// 单位M
  private float $fileAllowWidth = 1000;// 900px
  private array $ignoreWidthModule = ['banner'];// 900px

  /**
   * 参数检查
   */
  protected function check(): void
  {
    try {
      request()->validate([
        'file' => 'required',
        // 'module' => 'required',
        // 'type' => 'required',
      ]);
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = $exception->getMessage();
    }
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $file = request()->file('file');
    $module = request('module', 'image');
    // 主逻辑
    try {
      //检测
      if (!in_array($file->extension(), $this->fileAllowType)) {//类型限制
        throw  new \Exception("图片 " . $file->extension() . " 格式不支持");
      }
      if ($file->getSize() > $this->fileAllowSize * 1024 * 1024) {//大小限制
        throw  new \Exception("图片 " . (int)($file->getSize() / 1024 / 1024) . "M 超出{$this->fileAllowSize}M限制");
      }
      $img = Image::make($file);
      if ($img->getWidth() > $this->fileAllowWidth && !in_array($module,$this->ignoreWidthModule)) {//尺寸限制
        throw  new \Exception("图片宽度" . ($img->getWidth()) . "px 超出{$this->fileAllowWidth}px限制");
      }
      //压缩文件
      switch ($module) {
        case 'avatar':
          $img->resize(100, 100);
          break;
      }
      //目录创建
      $filePath = 'upload/' . $module . "/" . date('Ymd');
      if (!is_dir($filePath)) {
        // $oldumask = umask(0);
        mkdir($filePath, 0766, true);
        // umask($oldumask);
      }
      $saveFileName = 'upload/' . $module . "/" . date('Ymd') . '/' . md5($file) . '.' . $file->extension();
      $img->save($saveFileName);
      //插入图片表
      DB::table('file')->insert([
        'type' => 'image',
        'module' => $module,
        'path' => '/' . $saveFileName,
        'name' => $file->getClientOriginalName(),
        'size' => $file->getSize(),
        'createTime' => date('Y-m-d H:i:s'),
      ]);

      // 返回值
      $domain = config('app.url');
      switch ($module) {
        case 'avatar':
          $returnUrl = "/" . $saveFileName;
          break;
        default:
          $returnUrl = $domain . "/" . $saveFileName;
          break;
      }
      $this->result['url'] = $returnUrl;

    } catch (\Exception $exception) {
      $this->result['code'] = 1;
      $this->result['message'] = $exception->getMessage();
      return;
    }
  }
}
